package utils

import (
	"crypto/tls"
	"crypto/x509"
	"errors"
	"io"
	"net/http"
	"os"

	"cashway.com/cis/assistant/types"
)

func GetHttpClient(params types.CreateHttpsClientParams) (*http.Client, error) {
	if !params.NotInsecureSkipVerify && !params.IntermediateTerminalCertificate {
		return &http.Client{}, nil
	}

	caCertPool := x509.NewCertPool()
	if params.NotInsecureSkipVerify {
		if params.PemFilePath == "" {
			return nil, errors.New("NotInsecureSkipVerify 为 true 时，必须传入ca证书路径")
		}
		file, err := os.Open(params.PemFilePath)
		if err != nil {
			return nil, err
		}
		caCertBytes, err := io.ReadAll(file)
		if err != nil {
			return nil, err
		}
		caCertPool.AppendCertsFromPEM(caCertBytes)
	}

	var certificateList = []tls.Certificate{}
	if params.IntermediateTerminalCertificate {
		if params.CertFilePath == "" || params.KeyFilePath == "" {
			return nil, errors.New("InsecureSkipVerify 为 false 时，必须传入ca证书路径")
		}
		cliCert, err := tls.LoadX509KeyPair(params.CertFilePath, params.KeyFilePath)
		if err != nil {
			return nil, err
		}
		certificateList = append(certificateList, cliCert)
	}

	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				RootCAs:            caCertPool,                    // 校验服务端证书 [CA证书]
				Certificates:       certificateList,               // 客户端证书, 双向认证必须携带
				InsecureSkipVerify: !params.NotInsecureSkipVerify, // 不用校验服务器证书
			},
		},
	}

	return client, nil
}
